package com.hh.game.service.gateway.filter.security;

import com.hh.game.common.base.manager.session.Session;

import java.util.*;

/**
 * 保存安全数据，用户角色权限
 */
public class AuthorizingRealm {
    private Set<String> permissions;
    private Map<String, Object> attrs;
    private Session session;

    public AuthorizingRealm() {
        permissions = new HashSet<>();
        attrs = new HashMap<>();
    }

    public AuthorizingRealm(Set<String> permissions) {
        this.permissions = permissions == null ? new HashSet<>() : permissions;
    }

    public boolean isPermitted(String route, SecurityEnum securityEnum) {
        if(securityEnum == null){
            return true;
        }
        switch (securityEnum) {
            case NONE:
                return true;
            case LOGIN:
                return isLogin();
            default:
                return permissions.stream().anyMatch(p -> {
                    if(route.startsWith(p)){
                        int len = p.length();
                        if(len < route.length() && route.charAt(len) != '.'){
                            return false;
                        }
                        return true;
                    }
                    return false;
                });
        }
    }

    public Collection<String> getPermissions() {
        return permissions;
    }

    public void addPermission(String permission) {
        permissions.add(permission);
    }

    public void addPermission(Collection<String> permissions) {
        permissions.addAll(permissions);
    }

    public Object getAttr(String key) {
        return attrs.get(key);
    }

    public void addAttr(String key, Object val) {
        attrs.put(key, val);
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public boolean isLogin() {
        return session == null ? false : session.isLogin();
    }
}
